package com.bw.journal.list

import androidx.lifecycle.viewModelScope
import com.bw.common.mvi.BaseViewModel
import com.bw.journal.list.entity.JournalListEntity
import com.bw.journal.list.entity.JournalListResponseEntity
import com.bw.journal.list.entity.JournalListState
import kotlinx.coroutines.launch

class JournalListViewModel : BaseViewModel<JournalListRepo,JournalListState>() {

    private var page = 1

    override fun createRepo(): JournalListRepo {
        return JournalListRepo()
    }

    override fun createState(): JournalListState {
        return JournalListState(false,false,ArrayList())
    }

    fun refreshJournal(userId:Int){
        page = 1
        viewModelScope.launch {
            val map = HashMap<String,Any>()
            map["page"]=page
            map["userId"]=userId
            subFlow(repo.requestJournalList(map))
                .collect{
                    val listEntity : JournalListResponseEntity = it as JournalListResponseEntity
                    mutableContainer.updateUiState {
                        copy(refreshState = true, loadState = false, datas = listEntity.datas)
                    }
                }
        }
    }

    fun loadJournal(userId:Int){
        page += 1
        viewModelScope.launch {
            val map = HashMap<String,Any>()
            map["page"]=page
            map["userId"]=userId
            subFlow(repo.requestJournalList(map))
                .collect{
                    val listEntity : JournalListResponseEntity = it as JournalListResponseEntity
                    mutableContainer.updateUiState {
                        copy(refreshState = false, loadState = true, datas = listEntity.datas)
                    }
                }
        }
    }

}